//
//  ZYQRosterViewController.m
//  小庆聊天室
//
//  Created by 张毓庆 on 13-12-9.
//  Copyright (c) 2013年 张毓庆. All rights reserved.
//

#import "ZYQRosterViewController.h"
#import <CoreData/CoreData.h>
#import "ZYQAppDelegate.h"
#import "ZYQAddFriendViewController.h"
#import "ZYQChatMessageViewController.h"
#import "ZYQLoginUser.h"

@interface ZYQRosterViewController ()<NSFetchedResultsControllerDelegate,UIAlertViewDelegate>
{
    NSFetchedResultsController *_fetchedResultsController;
    
    //  要删除好友的表格索引
    NSIndexPath  *_removeIndexPath;
}
@end

@implementation ZYQRosterViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self setupFetchResultsController];
}

#pragma mark - AppDelegate 的助手方法
- (ZYQAppDelegate *)appDelegate
{
    return [[UIApplication sharedApplication] delegate];
}

#pragma mark - 初始化设置结果控制器 
- (void)setupFetchResultsController
{
    // 实例化NSManageredContext上下文
    NSManagedObjectContext *context = [[[self appDelegate] xmppRosterCoreDataStorage] mainThreadManagedObjectContext];
    
    // 实例化nsfetchRequest
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    
    // 实例化一个排序
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"jidStr" ascending:YES];
    
    [request setSortDescriptors:@[sort1,sort2]];
    
    // 实例化查询结果视图控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:@"sectionNum" cacheName:nil];
    
    // 设置代理
    [_fetchedResultsController setDelegate:self];
    
    // 查询数据
    NSError *error = nil;
    
    if (![_fetchedResultsController performFetch:&error])
    {
        NSLog(@"%@",error.localizedDescription);
    }
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _fetchedResultsController.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionData = [_fetchedResultsController sections];
    
    if (sectionData.count > 0)
    {
        id<NSFetchedResultsSectionInfo> sectionInfo = sectionData[section];
        
        return [sectionInfo numberOfObjects];
    }
    
    return 0;
}

#pragma mark - 表格行的方法
- (UIImage *)loadUserImage:(XMPPUserCoreDataStorageObject *)user
{
    // 判断user中是否包含头像，如果有直接返回
    if (user.photo)
    {
        return user.photo;
    }
    
    
    // 2. 如果没有头像，从用户的头像模块中提取用户头像
    NSData *photoData = [[xmppDelegate xmppvCardAvatarModule] photoDataForJID:user.jid];
    
    if (photoData) {
        return [UIImage imageWithData:photoData];
    }
    
    return [UIImage imageNamed:@"DefaultProfileHead"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"RosterCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    XMPPUserCoreDataStorageObject *user = [_fetchedResultsController objectAtIndexPath:indexPath];
    
    cell.textLabel.text = user.displayName;
    cell.imageView.image = [self loadUserImage:user];
    
    return cell;
}

#pragma mark 代理方法
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
}

#pragma mark - 表格的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"ChatSegue" sender:indexPath];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (UITableViewCellEditingStyleDelete == editingStyle)
    {
        // 取出用户
        XMPPUserCoreDataStorageObject *user = [_fetchedResultsController objectAtIndexPath:indexPath];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否删除好友" message:user.jidStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        // 记录住要删除的表格行索引
        _removeIndexPath = indexPath;
        
        [alert show];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // 取出控制器中的所有分组
    NSArray *array = [_fetchedResultsController sections];
    // 根据section的只取出对应的分组信息对象
    id<NSFetchedResultsSectionInfo> infoSection = array[section];
    
    NSString *stateName = nil;
    
    NSInteger state = [[infoSection name]integerValue];
    
    NSLog(@"在线状态%d",state);
    switch (state)
    {
        case 0:
            stateName = @"在线";
            break;
        case 1:
            stateName = @"离开";
            break;
        case 2:
            stateName = @"离线";
            break;
        default:
            stateName = @"未知";
            break;
    }
    
    return stateName;
}

#pragma mark - alertView的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        XMPPUserCoreDataStorageObject *user = [_fetchedResultsController objectAtIndexPath:_removeIndexPath];
        
        [[xmppDelegate xmppRoster] removeUser:user.jid];
    }
}

#pragma mark 准备Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSIndexPath *)indexPath
{
    // 判断是否跳往聊天界面
    if ([segue.identifier isEqualToString:@"ChatSegue"]) {
        ZYQChatMessageViewController *controller = segue.destinationViewController;
        
        // 获取当前选中的用户
        XMPPUserCoreDataStorageObject *user = [_fetchedResultsController objectAtIndexPath:indexPath];
        
        controller.bareJidStr = user.jidStr;
        controller.bareImage = user.photo;
        // 取出对话方的头像数据
        NSData *barePhoto = [[xmppDelegate xmppvCardAvatarModule] photoDataForJID:user.jid];
        controller.bareImage = [UIImage imageWithData:barePhoto];
        
        NSString *myStr = [ZYQLoginUser sharedZYQLoginUser].myJIDName;
        XMPPJID *myJID = [XMPPJID jidWithString:myStr];
        NSData *myPhoto = [[xmppDelegate xmppvCardAvatarModule] photoDataForJID:myJID];
        controller.myImage = [UIImage imageWithData:myPhoto];
    }
}

@end
